package a_doubleWrite;

/**
 * todo
 *
 * @author: luolidong
 * @create: 2021-07-22 08:56
 * @version: 1.0
 */
public class Trie {
    private class TireNode {
        boolean isEnd;
        TireNode[] next;

        public TireNode() {
            this.isEnd = false;
            this.next = new TireNode[26];
        }
    }

    private TireNode root;

    /**
     * Initialize your data structure here.
     */
    public Trie() {
        root = new TireNode();
    }

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        TireNode curNode = root;
        for (char c : word.toCharArray()) {
            if (curNode.next[c - 'a'] == null) {
                curNode.next[c - 'a'] = new TireNode();
            }
            curNode = curNode.next[c - 'a'];
        }
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {
        TireNode curNode = root;
        for (char c : word.toCharArray()) {
            if (curNode.next[c - 'a'] == null) {
                return false;
            }
            curNode = curNode.next[c - 'a'];
        }
        return curNode.isEnd;
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        TireNode curNode = root;
        for (char c : prefix.toCharArray()) {
            if (curNode.next[c - 'a'] == null) {
                return false;
            }
            curNode = curNode.next[c - 'a'];
        }
        return true;
    }
}
